<template>
  <view class="medical-container">
    <!-- 就诊卡选择区域 -->
    <view v-if="!selectedCard" class="card-selection-container">
      <van-notice-bar
        left-icon="volume-o"
        text="请选择您的就诊卡开始AI智能导诊服务"
        mode="closeable"
        color="#1989fa"
        background="#ecf9ff"
        class="notice-bar"
      />

      <!-- 就诊卡列表 -->
      <view class="card-list">
        <view
          v-for="card in medicalCards"
          :key="card.id"
          class="medical-card"
          @click="selectCard(card)"
        >
          <!-- 卡片顶部 -->
          <view class="card-header">
            <view class="card-left">
              <van-icon name="cross" color="#ff4444" size="20" />
              <text class="card-title">电子健康卡</text>
            </view>
            <view class="card-right">
              <text class="card-issuer">国家卫生健康委员会监制</text>
            </view>
          </view>

          <!-- 卡片中间 -->
          <view class="card-middle">
            <view class="card-info-left">
              <text class="patient-name">{{ card.patientName }}</text>
              <view class="card-tag self-tag">本人</view>
            </view>
            <view class="card-info-right">
              <view class="card-tag default-tag">默认</view>
            </view>
          </view>

          <!-- 卡片底部 -->
          <view class="card-bottom">
            <view class="card-number">{{
              formatBirthday(card.patientBirth)
            }}</view>
            <view class="select-btn">
              <text>选择此卡</text>
              <van-icon name="arrow" />
            </view>
          </view>
        </view>

        <!-- 空状态 -->
        <view
          v-if="medicalCards.length === 0 && !loadingCards"
          class="empty-state"
        >
          <van-empty description="暂无就诊卡" />
        </view>

        <!-- 加载状态 -->
        <view v-if="loadingCards" class="loading-state">
          <van-loading size="24px" />
          <text class="loading-text">正在加载就诊卡...</text>
        </view>
      </view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view
      v-if="selectedCard"
      class="chat-messages"
      scroll-y
      :scroll-top="scrollTop"
      scroll-with-animation
    >
      <!-- 当前选中的就诊卡信息 -->
      <view class="current-card-info">
        <text class="current-card-text"
          >当前就诊人：{{ selectedCard.patientName }}</text
        >
        <text class="change-card-btn" @click="changeCard">更换</text>
      </view>

      <view class="message-list">
        <!-- 消息项 -->
        <view
          v-for="(message, index) in messages"
          :key="index"
          class="message-item"
          :class="message.type"
        >
          <view
            class="message-avatar"
            v-if="message.type === 'ai' || message.type === 'recommendation'"
            :class="{
              'recommendation-avatar': message.type === 'recommendation',
            }"
          >
            <text
              class="avatar-icon"
              :class="{
                'recommendation-icon': message.type === 'recommendation',
              }"
            >
              {{ message.type === "recommendation" ? "🏥" : "🤖" }}
            </text>
          </view>

          <view class="message-bubble">
            <view class="message-content">
              <text class="message-text">{{ message.content }}</text>

              <!-- 科室推荐卡片 -->
              <view
                v-if="
                  message.type === 'recommendation' &&
                  message.departments &&
                  message.departments.length > 0
                "
                class="dept-cards-container"
              >
                <view class="dept-cards-title">
                  <text class="cards-title-text">推荐科室</text>
                  <text class="cards-count"
                    >{{ message.departments.length }}个</text
                  >
                </view>
                <view class="dept-cards-list">
                  <view
                    v-for="(dept, index) in message.departments"
                    :key="dept.deptId"
                    class="dept-card"
                    :class="{ primary: index === 0 }"
                    @click="selectDepartment(dept, index === 0)"
                  >
                    <view class="dept-card-header">
                      <view class="dept-icon">
                        <text class="icon-text">{{
                          getDeptIcon(dept.deptName)
                        }}</text>
                      </view>
                      <view class="dept-info">
                        <text class="dept-name">{{ dept.deptName }}</text>
                        <text class="dept-level" v-if="index === 0"
                          >首选推荐</text
                        >
                        <text class="dept-level" v-else>备选方案</text>
                      </view>
                      <view class="dept-action">
                        <text class="action-text">预约</text>
                        <van-icon name="arrow" size="12" />
                      </view>
                    </view>
                    <view class="dept-card-body" v-if="dept.description">
                      <text class="dept-description">{{
                        dept.description
                      }}</text>
                    </view>
                    <view class="dept-card-footer">
                      <view class="dept-tags">
                        <text class="dept-tag" v-if="message.urgency === 'high'"
                          >紧急</text
                        >
                        <text
                          class="dept-tag"
                          v-if="message.confidence && message.confidence > 0.8"
                          >高匹配度</text
                        >
                        <text class="dept-tag">专科</text>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="message-time">{{ message.time }}</view>
          </view>

          <view class="message-avatar" v-if="message.type === 'user'">
            <text class="avatar-icon">👤</text>
          </view>
        </view>

        <!-- AI正在分析 -->
        <view v-if="isThinking" class="message-item ai thinking">
          <view class="message-avatar">
            <text class="avatar-icon thinking-icon">🤖</text>
          </view>
          <view class="message-bubble thinking-bubble">
            <view class="message-content">
              <text class="message-text">AI医生正在分析中</text>
              <view class="thinking-dots">
                <text class="dot"></text>
                <text class="dot"></text>
                <text class="dot"></text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view v-if="selectedCard" class="input-section">
      <view class="input-container">
        <input
          class="message-input"
          v-model="inputText"
          placeholder="请简单描述您的症状..."
          :disabled="isThinking"
          @confirm="handleInitialInput"
        />
        <view
          class="send-button"
          :class="{
            active: inputText.trim() && !isThinking,
            disabled: isThinking,
          }"
          @click="handleInitialInput"
        >
          <text class="send-icon">📨</text>
        </view>
      </view>

      <!-- 快捷症状按钮 -->
      <view class="quick-symptoms">
        <text class="quick-title">常见症状快速选择：</text>
        <view class="quick-buttons">
          <view
            v-for="symptom in quickSymptoms"
            :key="symptom.key"
            class="quick-symptom-btn"
            :class="{ disabled: isThinking }"
            @click="isThinking ? null : selectQuickSymptom(symptom)"
          >
            <text class="symptom-icon">{{ symptom.icon }}</text>
            <text class="symptom-text">{{ symptom.label }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getPatientByUserId } from "@/api/patient";
import { getDeptDetailByDeptIds } from "@/api/department";
import type { OneDepartment } from "@/api/department";
import { useUserStore } from "@/stores";

interface Message {
  content: string;
  type: "user" | "ai" | "recommendation";
  time: string;
  departments?: OneDepartment[]; // 科室推荐信息
  urgency?: string; // 紧急程度
  confidence?: number; // 置信度
}

interface QuickSymptom {
  key: string;
  label: string;
  icon: string;
  value: string;
}

// 就诊卡接口定义
interface MedicalCard {
  id: number;
  patientName: string;
  patientBirth: string;
  patientGender: number;
  isDefault: boolean;
  isSelf: boolean;
}

const messages = ref<Message[]>([]);
const inputText = ref("");
const isThinking = ref(false);
const scrollTop = ref(0);
const userId = ref("");
const threadId = ref("");
const hasStartedChat = ref(false);

// 就诊卡相关状态
const selectedCard = ref<MedicalCard | null>(null);
const medicalCards = ref<MedicalCard[]>([]);
const loadingCards = ref(false);

// 初始化userStore
const userStore = useUserStore();

// 快捷症状选项
const quickSymptoms = ref<QuickSymptom[]>([
  { key: "pain", label: "疼痛", icon: "😣", value: "我感到疼痛" },
  { key: "fever", label: "发热", icon: "🤒", value: "我发烧了" },
  { key: "cough", label: "咳嗽", icon: "😷", value: "我咳嗽" },
  { key: "stomach", label: "胃部不适", icon: "🤢", value: "我胃部不舒服" },
  { key: "headache", label: "头痛", icon: "🤕", value: "我头痛" },
  { key: "fatigue", label: "疲劳", icon: "😴", value: "我感到疲劳" },
]);

onLoad(() => {
  console.log("AI智能导诊页面 onLoad");
  loadMedicalCards();
});

// 加载就诊卡数据
const loadMedicalCards = async () => {
  loadingCards.value = true;
  try {
    // 从userStore获取当前登录用户的ID
    const currentUserId =
      userStore.userInfo?.userId || userStore.userData?.user?.userId;

    if (!currentUserId) {
      uni.showToast({
        title: "用户未登录，请先登录",
        icon: "none",
      });
      return;
    }

    console.log("获取就诊卡列表 - 用户ID:", currentUserId);

    // 调用API获取就诊卡列表
    const response = await getPatientByUserId(currentUserId.toString());

    if (response.code === 200 && response.data) {
      medicalCards.value = response.data.map((card: any) => ({
        id: parseInt(card.patientId),
        patientName: card.patientName,
        patientBirth: card.patientBirth,
        patientGender: card.patientGender,
        isDefault: true,
        isSelf: true,
      }));

      console.log("加载就诊卡成功:", medicalCards.value);
    } else {
      console.warn("获取就诊卡失败:", response.msg);
      uni.showToast({
        title: response.msg || "获取就诊卡失败",
        icon: "none",
      });
    }
  } catch (error) {
    console.error("加载就诊卡失败:", error);
    uni.showToast({
      title: "网络错误，请稍后重试",
      icon: "none",
    });
  } finally {
    loadingCards.value = false;
  }
};

// 格式化生日显示
const formatBirthday = (birthday: string) => {
  return `生日：${birthday}`;
};

// 选择就诊卡
const selectCard = (card: MedicalCard) => {
  selectedCard.value = card;
  // 使用就诊卡ID作为userId
  userId.value = card.id.toString();
  threadId.value = "session_" + card.id.toString();

  console.log("选择就诊卡:", card);
  console.log("设置userId为:", userId.value);

  // 初始化聊天
  initChat();
};

// 更换就诊卡
const changeCard = () => {
  selectedCard.value = null;
  messages.value = [];
  hasStartedChat.value = false;
  userId.value = "";
  threadId.value = "";

  // 重新加载就诊卡
  loadMedicalCards();
};

// 初始化聊天
const initChat = () => {
  console.log("初始化AI智能导诊聊天");

  // 避免重复添加欢迎消息
  if (messages.value.length === 0) {
    // 添加欢迎消息，包含就诊人信息
    addMessage(
      `您好，${selectedCard.value?.patientName}！我是您的AI医疗助手。请描述您的症状，我会为您推荐最适合的科室。`,
      "ai"
    );
  }
};

const addMessage = (
  content: string,
  type: "user" | "ai" | "recommendation"
) => {
  const now = new Date();
  const time = `${now.getHours().toString().padStart(2, "0")}:${now
    .getMinutes()
    .toString()
    .padStart(2, "0")}`;

  messages.value.push({
    content,
    type,
    time,
  });

  nextTick(() => {
    scrollToBottom();
  });
};

const scrollToBottom = () => {
  scrollTop.value = scrollTop.value === 99999 ? 99998 : 99999;
};

// 处理用户输入
const handleInitialInput = async () => {
  if (!inputText.value.trim() || isThinking.value) {
    return;
  }

  const userMessage = inputText.value.trim();
  addMessage(userMessage, "user");
  inputText.value = "";
  hasStartedChat.value = true;

  // 直接调用AI对话接口
  await callDiagnosisChat(userMessage);
};

// 选择快捷症状
const selectQuickSymptom = async (symptom: QuickSymptom) => {
  addMessage(symptom.label, "user");
  hasStartedChat.value = true;

  // 直接调用AI对话接口
  await callDiagnosisChat(symptom.value);
};

// 调用诊断对话接口
const callDiagnosisChat = async (query: string) => {
  isThinking.value = true;

  try {
    const response = await (uni as any).request({
      url: "http://localhost:8080/diagnosis/chat",
      method: "POST",
      header: {
        "Content-Type": "application/json",
      },
      data: {
        query: query,
        userId: userId.value,
        threadId: threadId.value,
        isNewSession: messages.value.length <= 2,
      },
    });

    if (response.statusCode === 200 && response.data) {
      const aiResponse = response.data.response;

      // 显示AI回复
      if (aiResponse) {
        // 判断是否是科室推荐消息
        const isRecommendation =
          response.data.isCompleted && response.data.deptId;
        const messageType = isRecommendation ? "recommendation" : "ai";
        addMessage(aiResponse, messageType);
      }

      // 检查是否有科室推荐
      if (response.data.isCompleted && response.data.deptId) {
        await handleDepartmentRecommendation(response.data);
      }
    } else {
      addMessage("抱歉，暂时无法理解您的需求，请稍后重试。", "ai");
    }
  } catch (error) {
    console.error("AI对话失败:", error);
    addMessage("网络连接异常，请检查网络后重试。", "ai");
  } finally {
    isThinking.value = false;
  }
};

// 处理科室推荐，支持跳转功能
const handleDepartmentRecommendation = async (responseData: any) => {
  const deptId = responseData.deptId;
  const deptIds = responseData.deptIds || [deptId]; // 支持多科室ID数组
  const recommendedDepartment = responseData.recommendedDepartment;
  const alternativeDepartments = responseData.alternativeDepartments || [];

  // 记录推荐信息
  console.log("收到科室推荐:", {
    department: recommendedDepartment,
    deptId: deptId,
    deptIds: deptIds,
    alternativeDepartments: alternativeDepartments,
    urgency: responseData.urgency,
    confidence: responseData.confidence,
  });

  // 构建科室ID列表（主推荐 + 备选）
  const allDeptIds = [...new Set([...deptIds.filter((id) => id > 0)])]; // 去重并过滤无效ID
  console.log("allDeptIds", allDeptIds);
  if (allDeptIds.length > 0) {
    try {
      // 获取科室详细信息
      const deptDetailsResponse = await getDeptDetailByDeptIds(
        allDeptIds.map((id) => id.toString())
      );

      let departments: OneDepartment[] = [];
      if (deptDetailsResponse.code === 200 && deptDetailsResponse.data) {
        departments = deptDetailsResponse.data;

        // 按推荐优先级排序：主推荐科室排在前面
        departments.sort((a, b) => {
          const aIndex = deptIds.findIndex((id) => id.toString() === a.deptId);
          const bIndex = deptIds.findIndex((id) => id.toString() === b.deptId);
          return aIndex - bIndex;
        });
      } else {
        // 如果API获取失败，使用基础信息
        departments = [
          {
            deptId: deptId.toString(),
            deptName: recommendedDepartment || "内科",
            description: "推荐的科室",
          },
        ];
      }

      // 更新最后一条推荐消息，添加科室卡片信息
      const lastMessage = messages.value[messages.value.length - 1];
      if (lastMessage && lastMessage.type === "recommendation") {
        lastMessage.departments = departments;
        lastMessage.urgency = responseData.urgency;
        lastMessage.confidence = responseData.confidence;
      }

      console.log("科室卡片信息已添加:", departments);
    } catch (error) {
      console.error("获取科室详情失败:", error);
    }
  }

  // 延迟3秒后显示跳转提示，给用户时间查看推荐卡片
  setTimeout(() => {
    if (deptId && deptId > 0) {
      (uni as any).showModal({
        title: "科室推荐完成",
        content: `已为您推荐${recommendedDepartment}，是否立即前往预约挂号？`,
        confirmText: "立即预约",
        cancelText: "稍后查看",
        success: (res: any) => {
          if (res.confirm) {
            // 跳转到医生选择页面，携带科室ID和科室名称
            uni.navigateTo({
              url: `/pages/appointment/doctor-select?departmentId=${deptId}&departmentName=${encodeURIComponent(
                recommendedDepartment || ""
              )}`,
            });
          }
        },
      });
    } else {
      // 如果没有有效的科室ID，只显示推荐完成提示
      uni.showToast({
        title: "科室推荐完成",
        icon: "success",
        duration: 2000,
      });
    }
  }, 3000);
};

// 根据科室名称获取图标
const getDeptIcon = (deptName: string): string => {
  const iconMap: Record<string, string> = {
    内科: "🫀",
    外科: "🔪",
    心内科: "❤️",
    神经内科: "🧠",
    消化内科: "🍎",
    呼吸内科: "🫁",
    肾内科: "🔬",
    内分泌科: "⚖️",
    血液科: "🩸",
    风湿免疫科: "🦴",
    感染科: "🦠",
    急诊科: "🚨",
    骨科: "🦴",
    神经外科: "🧠",
    胸外科: "🫁",
    心外科: "❤️",
    泌尿外科: "🔬",
    肝胆外科: "🟨",
    血管外科: "🩸",
    妇科: "👩",
    产科: "🤱",
    儿科: "👶",
    眼科: "👁️",
    耳鼻喉科: "👂",
    口腔科: "🦷",
    皮肤科: "🧴",
    精神科: "💭",
    康复科: "🏃",
    中医科: "🌿",
  };

  // 查找匹配的科室名称
  for (const [key, icon] of Object.entries(iconMap)) {
    if (deptName.includes(key)) {
      return icon;
    }
  }

  return "🏥"; // 默认医院图标
};

// 选择科室进行预约
const selectDepartment = (dept: OneDepartment, isPrimary: boolean = false) => {
  console.log("选择科室:", dept, "是否首选:", isPrimary);

  uni.navigateTo({
    url: `/pages/appointment/doctor-select?departmentId=${
      dept.deptId
    }&departmentName=${encodeURIComponent(dept.deptName)}`,
  });
};
</script>

<style lang="scss">
// 现代化医疗主题配色
$primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
$secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
$success-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
$ai-gradient: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
$user-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
$bg-gradient: linear-gradient(
  135deg,
  #ffecd2 0%,
  #fcb69f 25%,
  #a8edea 50%,
  #d299c2 75%,
  #fef9d7 100%
);

// 主容器 - 白色背景
.medical-container {
  height: 100vh;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}

@keyframes gradientShift {
  0% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
  100% {
    background-position: 0% 50%;
  }
}

// 通知栏样式
.notice-bar {
  margin: 24rpx 20rpx;
  border-radius: 16rpx;
  background: #e8f5e8 !important;
  color: #07c160 !important;
}

// 就诊卡选择区域
.card-selection-container {
  flex: 1;
  padding: 0 20rpx;
  background: transparent;
}

.card-list {
  padding: 20rpx;
}

.medical-card {
  background: linear-gradient(135deg, #f0f8f0 0%, #e8f5e8 100%);
  border-radius: 20rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  position: relative;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);

  // 添加中国结图案背景
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: radial-gradient(
        circle at 20% 20%,
        rgba(255, 255, 255, 0.1) 2rpx,
        transparent 2rpx
      ),
      radial-gradient(
        circle at 80% 80%,
        rgba(255, 255, 255, 0.1) 2rpx,
        transparent 2rpx
      ),
      radial-gradient(
        circle at 40% 60%,
        rgba(255, 255, 255, 0.1) 2rpx,
        transparent 2rpx
      );
    background-size: 60rpx 60rpx, 80rpx 80rpx, 100rpx 100rpx;
    border-radius: 20rpx;
    pointer-events: none;
  }

  &:active {
    transform: translateY(-4rpx);
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  position: relative;
  z-index: 1;
}

.card-left {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-issuer {
  font-size: 24rpx;
  color: #666;
  text-align: right;
}

.card-middle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  position: relative;
  z-index: 1;
}

.card-info-left {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.patient-name {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.card-tag {
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 22rpx;
  color: white;

  &.self-tag {
    background: #07c160;
  }

  &.default-tag {
    background: #07c160;
  }
}

.card-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 1;
}

.card-number {
  font-size: 28rpx;
  color: #999;
}

.select-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background: #ff6b35;
  color: white;
  padding: 16rpx 24rpx;
  border-radius: 25rpx;
  font-size: 28rpx;
  font-weight: bold;
  transition: all 0.3s ease;

  &:active {
    background: #e85a2a;
    transform: translateY(2rpx);
  }
}

@keyframes shimmer {
  0% {
    transform: translateX(-100%) translateY(-100%) rotate(45deg);
  }
  100% {
    transform: translateX(100%) translateY(100%) rotate(45deg);
  }
}

// 当前选中的就诊卡信息
.current-card-info {
  background: rgba(25, 137, 250, 0.1);
  padding: 20rpx 24rpx;
  border-radius: 16rpx;
  margin: 20rpx 24rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 6rpx solid #1989fa;

  .current-card-text {
    font-size: 28rpx;
    color: #1989fa;
    font-weight: 500;
  }

  .change-card-btn {
    font-size: 26rpx;
    color: #1989fa;
    text-decoration: underline;
    padding: 8rpx 16rpx;
  }
}

// 聊天消息区域
.chat-messages {
  flex: 1;
  padding: 30rpx 24rpx;
  background: transparent;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.message-item {
  display: flex;
  align-items: flex-end;
  gap: 16rpx;
  animation: messageSlideIn 0.5s ease-out;

  &.user {
    flex-direction: row-reverse;

    .message-bubble {
      background: $user-gradient;
      color: white;
      margin-left: 60rpx;
      border: none;
      box-shadow: 0 4px 20px rgba(102, 126, 234, 0.3);

      &::before {
        content: "";
        position: absolute;
        bottom: 10rpx;
        right: -8rpx;
        width: 0;
        height: 0;
        border: 8rpx solid transparent;
        border-left-color: #764ba2;
      }

      .message-time {
        color: rgba(255, 255, 255, 0.8);
      }
    }
  }

  &.ai {
    .message-bubble {
      background: rgba(255, 255, 255, 0.9);
      backdrop-filter: blur(20px);
      color: #4a5568;
      margin-right: 60rpx;
      border: 1px solid rgba(255, 255, 255, 0.3);
      box-shadow: 0 4px 20px rgba(168, 237, 234, 0.3);

      &::before {
        content: "";
        position: absolute;
        bottom: 10rpx;
        left: -8rpx;
        width: 0;
        height: 0;
        border: 8rpx solid transparent;
        border-right-color: rgba(255, 255, 255, 0.9);
      }
    }
  }

  &.recommendation {
    .message-bubble {
      background: $success-gradient;
      color: white;
      margin-right: 60rpx;
      border: none;
      box-shadow: 0 4px 20px rgba(79, 172, 254, 0.4);
      position: relative;
      overflow: hidden;

      &::before {
        content: "";
        position: absolute;
        bottom: 10rpx;
        left: -8rpx;
        width: 0;
        height: 0;
        border: 8rpx solid transparent;
        border-right-color: #00f2fe;
      }

      &::after {
        content: "✨";
        position: absolute;
        top: -10rpx;
        right: -10rpx;
        font-size: 24rpx;
        animation: sparkle 2s ease-in-out infinite;
      }

      .message-text {
        font-weight: 600;
        text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

// 科室推荐卡片样式
.dept-cards-container {
  margin-top: 20rpx;
  padding: 0;
}

.dept-cards-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 0 4rpx;

  .cards-title-text {
    font-size: 28rpx;
    font-weight: 600;
    color: #2d3748;
  }

  .cards-count {
    font-size: 24rpx;
    color: #718096;
    background: rgba(113, 128, 150, 0.1);
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
  }
}

.dept-cards-list {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.dept-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  padding: 20rpx;
  border: 2rpx solid rgba(74, 85, 104, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 6rpx;
    height: 100%;
    background: #e2e8f0;
    transition: background 0.3s ease;
  }

  &.primary {
    border-color: rgba(79, 172, 254, 0.3);
    background: linear-gradient(
      135deg,
      rgba(79, 172, 254, 0.05) 0%,
      rgba(0, 242, 254, 0.05) 100%
    );

    &::before {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }

    .dept-card-header .dept-info .dept-level {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: white;
    }

    .dept-action {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      color: white;
    }
  }

  &:active {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 25rpx rgba(79, 172, 254, 0.2);
  }
}

.dept-card-header {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.dept-icon {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;

  .icon-text {
    font-size: 28rpx;
    filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2));
  }
}

.dept-info {
  flex: 1;

  .dept-name {
    font-size: 32rpx;
    font-weight: 600;
    color: #2d3748;
    display: block;
    margin-bottom: 6rpx;
  }

  .dept-level {
    font-size: 22rpx;
    color: #718096;
    background: rgba(113, 128, 150, 0.1);
    padding: 4rpx 10rpx;
    border-radius: 10rpx;
    display: inline-block;
  }
}

.dept-action {
  display: flex;
  align-items: center;
  gap: 6rpx;
  background: rgba(74, 85, 104, 0.1);
  color: #4a5568;
  padding: 10rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  font-weight: 500;
  transition: all 0.3s ease;

  .action-text {
    font-size: 24rpx;
  }
}

.dept-card-body {
  margin-bottom: 16rpx;

  .dept-description {
    font-size: 26rpx;
    color: #718096;
    line-height: 1.4;
  }
}

.dept-card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dept-tags {
  display: flex;
  gap: 8rpx;
  flex-wrap: wrap;
}

.dept-tag {
  font-size: 20rpx;
  color: #718096;
  background: rgba(113, 128, 150, 0.1);
  padding: 4rpx 10rpx;
  border-radius: 10rpx;
  border: 1rpx solid rgba(113, 128, 150, 0.2);
}

@keyframes messageSlideIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes sparkle {
  0%,
  100% {
    transform: rotate(0deg) scale(1);
  }
  50% {
    transform: rotate(180deg) scale(1.2);
  }
}

// 头像 - 现代化设计
.message-avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
  position: relative;

  .avatar-icon {
    font-size: 28rpx;
    filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));

    &.thinking-icon {
      animation: bounce 2s infinite;
    }
  }

  &.recommendation-avatar {
    background: $success-gradient;
    border-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 4px 20px rgba(79, 172, 254, 0.4);

    .avatar-icon {
      color: white;
      animation: glow 3s ease-in-out infinite;
    }
  }
}

@keyframes glow {
  0%,
  100% {
    filter: drop-shadow(0 0 5px rgba(255, 255, 255, 0.5));
  }
  50% {
    filter: drop-shadow(0 0 15px rgba(255, 255, 255, 0.8));
  }
}

// 消息气泡 - 现代化设计
.message-bubble {
  max-width: 75%;
  padding: 20rpx 24rpx;
  border-radius: 24rpx 24rpx 24rpx 6rpx;
  position: relative;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;

  .message-content {
    .message-text {
      font-size: 30rpx;
      line-height: 1.5;
      word-wrap: break-word;
    }
  }

  .message-time {
    font-size: 22rpx;
    color: #a0aec0;
    margin-top: 8rpx;
  }
}

// 输入区域 - 现代化设计
.input-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-top: 1px solid rgba(255, 255, 255, 0.3);
  padding: 20rpx 24rpx 40rpx;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 3;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60rpx;
    height: 6rpx;
    background: rgba(0, 0, 0, 0.1);
    border-radius: 3rpx;
  }
}

.input-container {
  display: flex;
  align-items: center;
  gap: 16rpx;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 50rpx;
  padding: 8rpx;
  border: 1px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.1);
  margin-bottom: 20rpx;
}

.message-input {
  flex: 1;
  background: transparent;
  border: none;
  padding: 16rpx 20rpx;
  font-size: 28rpx;
  color: #4a5568;

  &::placeholder {
    color: #a0aec0;
  }
}

.send-button {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: $primary-gradient;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &.active {
    background: $primary-gradient;
    box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
    transform: scale(1.05);

    .send-icon {
      color: white;
      transform: scale(1.1);
    }
  }

  &.disabled {
    background: #f7fafc;

    .send-icon {
      color: #cbd5e0;
    }
  }

  .send-icon {
    font-size: 24rpx;
    transition: all 0.3s ease;
    position: relative;
    z-index: 1;
  }
}

// 快捷症状按钮 - 现代化卡片设计
.quick-symptoms {
  margin-top: 20rpx;

  .quick-title {
    font-size: 26rpx;
    color: #4a5568;
    margin-bottom: 16rpx;
    font-weight: 600;
  }

  .quick-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 12rpx;
  }
}

.quick-symptom-btn {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  padding: 14rpx 20rpx;
  border-radius: 50rpx;
  border: 1px solid rgba(255, 255, 255, 0.6);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(
      90deg,
      transparent,
      rgba(255, 255, 255, 0.6),
      transparent
    );
    transition: left 0.5s;
  }

  &:active:not(.disabled) {
    background: rgba(102, 126, 234, 0.9);
    backdrop-filter: blur(20px);
    transform: translateY(-2rpx) scale(0.98);
    box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);

    &::before {
      left: 100%;
    }

    .symptom-text {
      color: white;
    }

    .symptom-icon {
      transform: scale(1.1);
    }
  }

  &.disabled {
    opacity: 0.4;
    background: rgba(247, 250, 252, 0.8);

    .symptom-text {
      color: #cbd5e0;
    }

    .symptom-icon {
      opacity: 0.5;
    }
  }

  .symptom-text {
    font-size: 24rpx;
    color: #4a5568;
    font-weight: 500;
    transition: color 0.3s ease;
  }

  .symptom-icon {
    font-size: 24rpx;
    transition: transform 0.3s ease;
    filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.1));
  }
}

// AI思考状态 - 现代化动画
.thinking-dots {
  display: flex;
  gap: 4rpx;
  margin-top: 8rpx;

  .dot {
    width: 8rpx;
    height: 8rpx;
    border-radius: 50%;
    background: #667eea;
    animation: wave 1.4s ease-in-out infinite;

    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes wave {
  0%,
  60%,
  100% {
    transform: translateY(0);
    opacity: 0.4;
  }
  30% {
    transform: translateY(-10rpx);
    opacity: 1;
  }
}

@keyframes bounce {
  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-6rpx);
  }
  60% {
    transform: translateY(-3rpx);
  }
}

// 响应式适配
@media (max-width: 750px) {
  .message-item {
    &.user .message-bubble {
      margin-left: 40rpx;
    }
    &.ai .message-bubble,
    &.recommendation .message-bubble {
      margin-right: 40rpx;
    }
  }

  .quick-buttons {
    justify-content: center;
  }
}

// 加载状态
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 40rpx;
  color: #667eea;
}

// 卡片选择相关样式
.card-header,
.card-middle,
.card-bottom {
  position: relative;
  z-index: 1;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.patient-name {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.select-btn {
  background: #ff6b35;
  color: white;
  padding: 16rpx 24rpx;
  border-radius: 25rpx;
  font-size: 28rpx;
  font-weight: bold;
  transition: all 0.3s ease;

  &:active {
    background: #e85a2a;
    transform: translateY(2rpx);
  }
}

.empty-state {
  padding: 100rpx 0;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
  gap: 16rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #969799;
}
</style>
